package service

import (
	"context"
	pb "doctor-srv/basic/proto"
	"doctor-srv/basic/config"
	"doctor-srv/handler/model"
)

type AttachmentService struct {
	pb.UnimplementedAttachmentServer
}

// UploadAttachment 上传附件
func (s *AttachmentService) UploadAttachment(ctx context.Context, req *pb.UploadAttachmentReq) (*pb.UploadAttachmentResp, error) {
	attachment := model.Attachment{
		UserID:         req.UserId,
		UserType:       int(req.UserType),
		AttachmentType: int(req.AttachmentType),
		FileName:       req.FileName,
		FileUrl:        req.FileUrl,
	}

	if err := attachment.CreateAttachment(config.DB); err != nil {
		return nil, err
	}

	return &pb.UploadAttachmentResp{
		AttachmentId: int64(attachment.ID),
	}, nil
}

// GetAttachmentList 获取附件列表
func (s *AttachmentService) GetAttachmentList(ctx context.Context, req *pb.GetAttachmentListReq) (*pb.GetAttachmentListResp, error) {
	attachments, total, err := model.GetAttachmentList(
		config.DB,
		req.UserId,
		int(req.AttachmentType),
		int(req.Page),
		int(req.PageSize),
	)
	if err != nil {
		return nil, err
	}

	var attachmentInfos []*pb.AttachmentInfo
	for _, attachment := range attachments {
		attachmentInfos = append(attachmentInfos, &pb.AttachmentInfo{
			AttachmentId:   int64(attachment.ID),
			FileName:       attachment.FileName,
			FileUrl:        attachment.FileUrl,
			AttachmentType: int32(attachment.AttachmentType),
			CreatedAt:      attachment.CreatedAt.Unix(),
		})
	}

	return &pb.GetAttachmentListResp{
		Attachments: attachmentInfos,
		Total:       total,
	}, nil
}

// SetAttachmentPermission 设置附件权限
func (s *AttachmentService) SetAttachmentPermission(ctx context.Context, req *pb.SetAttachmentPermissionReq) (*pb.SetAttachmentPermissionResp, error) {
	err := model.SetAttachmentPermissions(config.DB, req.AttachmentId, req.AuthorizedUserIds)
	if err != nil {
		return &pb.SetAttachmentPermissionResp{
			Success: false,
			Message: "设置权限失败",
		}, err
	}

	return &pb.SetAttachmentPermissionResp{
		Success: true,
		Message: "设置权限成功",
	}, nil
}

